<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.phone"
        placeholder="请输入手机号"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.name"
        placeholder="请输入商户名称"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-date-picker
        v-model="listQuery.startDay"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        placeholder="选择开始日期时间"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-date-picker
        v-model="listQuery.endDay"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        placeholder="选择结束日期时间"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate(2)"
      >
        添加商户
      </el-button>
    </div>

    <el-table
      :key="key"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        label="序号"
        prop="id"
        align="center"
        width="50"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="company"
        label="商户名称"
        align="center"
        width="120"
      />
      <el-table-column
        prop="name"
        label="负责人"
        align="center"
        width="90"
      />
      <el-table-column
        prop="phone"
        label="联系电话"
        align="center"
        width="100"
      />

      <el-table-column
        label="主卡数量"
        width="80"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag size="medium" class="master-card"
                  @click="mainCard(scope.row)"
          > {{ scope.row.masterNum }}
          </el-tag>

        </template>
      </el-table-column>

      <el-table-column
        prop="subNum"
        label="子卡数量"
        align="center"
        width="70"
      />

      <el-table-column
        prop="unSubNum"
        label="未分配子卡"
        align="center"
        width="90"
      />
      <el-table-column
        prop="hangMasterNum"
        label="高挂主卡"
        align="center"
        width="70"
      />
      <el-table-column
        prop="unhangMasterNum"
        label="非高挂主卡"
        align="center"
        width="90"
      />

      <el-table-column
        prop="currenMoney"
        label="卡面总额(元)"
        width="100"
        align="center"
      >
      </el-table-column>

      <el-table-column
        prop="unCurrenMoney"
        label="卡面未分配余额(元)"
        align="center"
        width="130"
      />
      <el-table-column
        prop="payMoney"
        label="应付金额(元)"
        align="center"
        width="100"
      />
      <el-table-column
        prop="payMoney"
        label="已支付(元)"
        align="center"
        width="100"
      />
      <el-table-column
        prop="driverPayMoney"
        label="欠款金额(元)"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
            {{scope.row.payMoney - scope.row.driverPayMoney}}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>

          <!-- <router-link :to="'/bankCard/'+scope.row.id"> -->
          <!-- <el-button
            type="warning"
            size="mini"
            @click="detail(scope.row)"
          >详情
          </el-button> -->
          <!-- </router-link> -->

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      top="2vh"
      width="680px"
    >
      <el-form
        ref="temp"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
        style="width:550px; margin-left:50px;"
      >
        <el-form-item
          label="商户名称"
          prop="company"
        >
          <el-input v-model="temp.company"/>
        </el-form-item>

        <el-form-item
          label="负责人"
          prop="name"
        >
          <el-input v-model="temp.name"/>
        </el-form-item>

        <el-form-item
          label="联系电话"
          prop="phone"
        >
          <el-input
            v-model="temp.phone"
            :disabled="editPhone"
          />
        </el-form-item>

        <provinceData
          ref="provinceData"
          :temp="temp"
          @listen="getProvince"
          @ifValid="ifValid"
        />

        <el-form-item
          label="身份证正面"
          prop="idCardPositive"
        >
          <el-input
            v-model="temp.idCardPositive"
            style="display:none"
          />
          <addImgall
            ref="mychild"
            :image-url="temp.idCardPositive "
            @imgUrl="getImg1"
          />
        </el-form-item>

        <el-form-item
          label="身份证反面"
          prop="idCardNegative"
        >
          <el-input
            v-model="temp.idCardNegative"
            style="display:none"
          />
          <addImgall
            ref="mychild"
            :image-url="temp.idCardNegative "
            @imgUrl="getImg2"
          />
        </el-form-item>

        <el-form-item
          v-permission="['admin']"
          label="所属代理"
          prop="parentId"
        >
          <el-select
            v-model="temp.parentId"
            class="filter-item"
          >
            <el-option
              v-for="item in allAgent"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="createData()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>

    </el-dialog>

  </div>
</template>
<script>
  import permission from "@/directive/permission/index.js"; // 权限判断指令
  import checkPermission from "@/utils/permission"; // 权限判断函数

  import {
    getOilSupplyList,
    createOilSupply,
    getallAgent,
    business
  } from "@/api/v1";
  import {supplyUnBind} from "@/api/user";

  import waves from "@/directive/waves"; // Waves directive
  import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
  import {parseTime} from "@/utils";
  import addImgall from "@/components/img";
  import provinceData from "@/components/province";

  export default {
    directives: {waves, permission},
    components: {Pagination, addImgall, provinceData},
    data() {
      return {
        editPhone: true,
        imageUrl: "",
        tableData: [],
        allAgent: [],
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        cooperation: [],
        listQuery: {
          page: 1,
          limit: 20,
          sort: "+id",
          phone: "",
          startDay: "",
          endDay: ""
        },
        key: 1, // table key
        dialogFormVisible: false,
        rules: {
          name: [{required: true, message: "请输入名称", trigger: "blur"}],
//        parentId: [
//          { required: true, message: "请选择所属省代", trigger: "change" }
//        ],
          idCardPositive: [
            {required: true, message: "请上传身份证正面", trigger: "change"}
          ],
          idCardNegative: [
            {required: true, message: "请上传身份证反面", trigger: "change"}
          ],
          phone: [{required: true, message: "请输入电话", trigger: "blur"}],
          legalPerson: [
            {required: true, message: "请输入姓名", trigger: "blur"}
          ],
          company: [
            {required: true, message: "请输入公司名称", trigger: "blur"}
          ]
        },
        dialogStatus: "",
        textMap: {
          update: "编辑",
          create: "新增"
        },
        temp: {
          idCardNegative: "",
          name: "",
          phone: "",
          address: "",
          legalPerson: "",
          provinceCode: "",
          cityCode: "",
          areaCode: "",
          parentId: ""
        },
        isAdmin: true
      };
    },
    watch: {
      checkboxVal(valArr) {
        this.formThead = this.formTheadOptions.filter(
          i => valArr.indexOf(i) >= 0
        );
        this.key = this.key + 1; // 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
      }
    },

    created() {
      const id = this.$route.query.id;
      this.listQuery.cooperation = id;
      console.log(id);
      this.getList();
      if (checkPermission(["admin"])) {
        this.getList2();
      } else {
        this.isAdmin = false;
      }
    },
    methods: {
      mainCard(row) {
        console.log(row);
        this.$router.push({
          path: "/mainCard",
          query: {
            id: row.id
          }
        });
      },
      getProvince(data) {
        console.log("0000000000000000000000");
        console.log(data);
        this.temp.provinceCode = data.provinceCode;
        this.temp.cityCode = data.cityCode;
        this.temp.areaCode = data.areaCode;
        this.temp.address = data.address;
      },
      detail(row) {
        console.log(row);
        this.$router.push({
          path: "/bankCard",
          query: {
            relationId: row.id,
            relationType: 1,
            currentMoney: row.currentMoney,
            phone: row.phone,
            name: row.name,
            type: 2 // 1是省代  2是商户
          }
        });
      },
      getImg1(data) {
        console.log(data);
        console.log(this);
        this.temp.idCardPositive = data;
      },
      getImg2(data) {
        console.log(data);
        this.temp.idCardNegative = data;
      },
      resetTemp() {
        this.temp = {
          role: "",
          name: "",
          phone: "",
          id: "",
          company: "",
          provinceCode: "",
          cityCode: "",
          areaCode: "",
          address: "",
          idCardPositive: "",
          idCardNegative: ""
        };
        // this.$refs.mychild.resetImg();
      },
      handleCreate(role) {
        this.resetTemp();
        this.temp.role = role;
        console.log(this.temp);
        this.dialogStatus = "create";
        this.dialogFormVisible = true;
        this.editPhone = false;
        this.$nextTick(() => {
          this.$refs["temp"].clearValidate();
        });
        this.$refs.provinceData.clearProvinceDate();
      },
      unBind(row) {
        this.$confirm(
          "此操作将取消该微信账号在小程序端的所有授权登陆, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            supplyUnBind(row).then(res => {
              console.log(res);
              this.$notify({
                title: "消息",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            });
          })
          .catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // });
          });
      },
      ifValid(ifValid) {
        if (ifValid) {
          this.$refs["temp"].validate(valid => {
            if (valid) {
              createOilSupply(this.temp).then(res => {
                // this.list.unshift(this.temp);
                this.dialogFormVisible = false;
                this.$notify({
                  title: "成功",
                  message: res.msg,
                  type: "success",
                  duration: 2000
                });
                this.getList();
              });
            }
          });
        }
      },
      createData() {
        this.$refs.provinceData.submitForm();
        this.$refs["temp"].validate(valid => {
          return valid;
        });
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row); // copy obj
        console.log(row);
        this.dialogStatus = "update";
        this.dialogFormVisible = true;
        this.$refs.provinceData.getCityData();
        this.editPhone = true;
        this.$nextTick(() => {
          this.$refs["temp"].clearValidate();
        });
        this.$refs.provinceData.clearProvinceDate();
      },
      getList() {
        this.listLoading = true;
        business(this.listQuery).then(res => {
          this.tableData = res.data.records;
          this.total = Number(res.data.total);
          console.log(this.tableData);
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false;
          }, 1.5 * 1000);
        });
      },
      getList2() {
        this.listLoading = true;
        getallAgent(this.listQuery).then(res => {
          this.allAgent = res.data;
          console.log(this.allAgent);
        });
      },
      getCooperationAll() {
        cooperationAll().then(res => {
          this.cooperation = res.data;

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false;
          }, 1.5 * 1000);
        });
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      }
    }
  };
</script>
<style scoped>
  .master-card {
    cursor: pointer;
  }
</style>

